<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>上传电子书 - ZLibLike平台</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <div th:replace="~{commons/header :: header}"></div>
    
    <div class="container mt-4">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h3 class="mb-0">上传电子书</h3>
                    </div>
                    <div class="card-body">
                        <form id="uploadForm" enctype="multipart/form-data">
                            <!-- CSRF 令牌 -->
                            <input type="hidden" name="_csrf" th:value="${_csrf?.token}" />
                            
                            <div class="alert alert-info">
                                <strong>提示：</strong> 支持的文件格式：<span id="supportedFormats">PDF, EPUB, MOBI</span>
                            </div>
                            
                            <div id="errorAlert" class="alert alert-danger d-none"></div>
                            <div id="successAlert" class="alert alert-success d-none"></div>
                            
                            <div class="form-group row">
                                <label for="title" class="col-md-3 col-form-label">书名 <span class="text-danger">*</span></label>
                                <div class="col-md-9">
                                    <input type="text" class="form-control" id="title" name="title" required>
                                </div>
                            </div>
                            
                            <div class="form-group row">
                                <label for="author" class="col-md-3 col-form-label">作者 <span class="text-danger">*</span></label>
                                <div class="col-md-9">
                                    <input type="text" class="form-control" id="author" name="author" required>
                                </div>
                            </div>
                            
                            <div class="form-group row">
                                <label for="publisher" class="col-md-3 col-form-label">出版社</label>
                                <div class="col-md-9">
                                    <input type="text" class="form-control" id="publisher" name="publisher">
                                </div>
                            </div>
                            
                            <div class="form-group row">
                                <label for="pubYear" class="col-md-3 col-form-label">出版年份</label>
                                <div class="col-md-9">
                                    <input type="number" class="form-control" id="pubYear" name="pubYear" min="1800" max="2099">
                                </div>
                            </div>
                            
                            <div class="form-group row">
                                <label for="language" class="col-md-3 col-form-label">语言</label>
                                <div class="col-md-9">
                                    <select class="form-control" id="language" name="language">
                                        <option value="中文">中文</option>
                                        <option value="英文">英文</option>
                                        <option value="日文">日文</option>
                                        <option value="法文">法文</option>
                                        <option value="德文">德文</option>
                                        <option value="西班牙文">西班牙文</option>
                                        <option value="俄文">俄文</option>
                                        <option value="其他">其他</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="form-group row">
                                <label for="isbn10" class="col-md-3 col-form-label">ISBN-10</label>
                                <div class="col-md-9">
                                    <input type="text" class="form-control" id="isbn10" name="isbn10" pattern="[0-9]{10}">
                                    <small class="form-text text-muted">10位数字，无连字符</small>
                                </div>
                            </div>
                            
                            <div class="form-group row">
                                <label for="isbn13" class="col-md-3 col-form-label">ISBN-13</label>
                                <div class="col-md-9">
                                    <input type="text" class="form-control" id="isbn13" name="isbn13" pattern="[0-9]{13}">
                                    <small class="form-text text-muted">13位数字，无连字符</small>
                                </div>
                            </div>
                            
                            <div class="form-group row">
                                <label for="bookFile" class="col-md-3 col-form-label">电子书文件 <span class="text-danger">*</span></label>
                                <div class="col-md-9">
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input" id="bookFile" name="bookFile" required>
                                        <label class="custom-file-label" for="bookFile">选择文件</label>
                                    </div>
                                    <small class="form-text text-muted">最大文件大小：100MB</small>
                                </div>
                            </div>
                            
                            <div class="form-group row">
                                <label for="coverFile" class="col-md-3 col-form-label">封面图片</label>
                                <div class="col-md-9">
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input" id="coverFile" name="coverFile" accept="image/*">
                                        <label class="custom-file-label" for="coverFile">选择文件</label>
                                    </div>
                                    <small class="form-text text-muted">建议尺寸：600x800像素，最大文件大小：2MB</small>
                                </div>
                            </div>
                            
                            <div class="form-group row">
                                <div class="col-md-9 offset-md-3">
                                    <button type="submit" class="btn btn-primary" id="uploadBtn">
                                        <i class="fa fa-upload"></i> 上传电子书
                                    </button>
                                    <button type="reset" class="btn btn-secondary ml-2">
                                        <i class="fa fa-refresh"></i> 重置
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div th:replace="~{commons/footer :: footer}"></div>
    
    <script src="/js/jquery-3.6.0.min.js"></script>
    <script src="/js/bootstrap.bundle.min.js"></script>
    <script th:inline="javascript">
        $(document).ready(function() {
            // 获取CSRF令牌
            const csrfToken = $("input[name='_csrf']").val();
            
            // 获取支持的文件格式
            fetch('/api/book/supported-formats', {
                method: 'GET',
                headers: {
                    'X-CSRF-TOKEN': csrfToken
                },
                credentials: 'include'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 200) {
                        $('#supportedFormats').text(data.data.join(', '));
                    }
                })
                .catch(error => console.error('Error:', error));
            
            // 文件选择后显示文件名
            $('.custom-file-input').on('change', function() {
                let fileName = $(this).val().split('\\').pop();
                $(this).next('.custom-file-label').html(fileName);
            });
            
            // ISBN校验
            $('#isbn10, #isbn13').on('blur', function() {
                const isbn = $(this).val().trim();
                if (isbn) {
                    checkIsbn(isbn);
                }
            });
            
            // 检查ISBN是否已存在
            function checkIsbn(isbn) {
                fetch(`/api/book/check-isbn?isbn=${isbn}`, {
                    method: 'GET',
                    headers: {
                        'X-CSRF-TOKEN': csrfToken
                    },
                    credentials: 'include'
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 200 && data.data === true) {
                            alert('该ISBN已存在，请检查输入是否正确');
                        }
                    })
                    .catch(error => console.error('Error:', error));
            }
            
            // 表单提交
            $('#uploadForm').submit(function(e) {
                e.preventDefault();
                
                // 隐藏提示信息
                $('#errorAlert').addClass('d-none');
                $('#successAlert').addClass('d-none');
                
                // 禁用上传按钮
                $('#uploadBtn').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 上传中...');
                
                // 构造FormData
                const formData = new FormData(this);
                
                // 获取CSRF令牌
                const csrfToken = $("input[name='_csrf']").val();
                
                // 发送请求
                fetch('/api/book/upload', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-CSRF-TOKEN': csrfToken
                    },
                    credentials: 'include' // 允许携带凭证
                })
                .then(response => response.json())
                .then(data => {
                    // 启用上传按钮
                    $('#uploadBtn').prop('disabled', false).html('<i class="fa fa-upload"></i> 上传电子书');
                    
                    if (data.status === 200) {
                        // 显示成功信息
                        $('#successAlert').html(`上传成功！书籍ID：${data.data.bookId}，标题：${data.data.title}`).removeClass('d-none');
                        
                        // 重置表单
                        $('#uploadForm')[0].reset();
                        $('.custom-file-label').html('选择文件');
                        
                        // 滚动到顶部
                        $('html, body').animate({ scrollTop: 0 }, 'fast');
                        
                        // 3秒后跳转到书籍详情页
                        setTimeout(() => {
                            window.location.href = `/book-details.html?id=${data.data.bookId}`;
                        }, 3000);
                    } else {
                        // 显示错误信息
                        $('#errorAlert').html(data.message).removeClass('d-none');
                        
                        // 滚动到顶部
                        $('html, body').animate({ scrollTop: 0 }, 'fast');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    $('#uploadBtn').prop('disabled', false).html('<i class="fa fa-upload"></i> 上传电子书');
                    $('#errorAlert').html('上传失败，请稍后重试').removeClass('d-none');
                    $('html, body').animate({ scrollTop: 0 }, 'fast');
                });
            });
        });
    </script>
</body>
</html> 